<?php

namespace common\components\zhiling;

use common\Tools;
use common\wodrow\Rsa;
use GuzzleHttp\Client;
use yii\base\Component;

class ZhiLing extends Component
{
    public $baseUri;
    public $appKey;
    public $appSecret;
    public $sign;

    private function sign($params)
    {
        ksort($params);
        $pair = [];
        foreach ($params as $k => $v) {
            $pair[] = $k . '=' . $v;
        }
        $str = implode('&', $pair);
        return strtolower(md5($str . '&key=' . $this->appSecret));
    }

    protected function assembleParams($params)
    {
        $rsaUtil = new Rsa(\Yii::getAlias('@common/config/filedata/zhiling/private.pem'), \Yii::getAlias('@common/config/filedata/zhiling/public.pem'));
        $data = $rsaUtil->publicEncrypt(Tools::toJson($params));

        return [
            'app_key' => $this->appKey,
            'version' => 'v1',
            'data' => $data,
            'sign' => $this->sign($params),
        ];
    }

    public function sendSms($params)
    {
        $client = new Client(['base_uri' => $this->baseUri]);
        $form_params = $this->assembleParams($params);
        $resp = $client->request('post', '', [
            'form_params' => $form_params
        ]);
        var_dump($resp->getBody()->getContents());
    }
}